package cn.aaa.service.impl;

import cn.aaa.constants.UserType;
import cn.aaa.mapper.CustomerSummaryMapper;
import cn.aaa.openFeign.UaaOpenFeign;
import cn.aaa.pojo.domain.Customer;
import cn.aaa.mapper.CustomerMapper;
import cn.aaa.pojo.domain.CustomerSummary;
import cn.aaa.pojo.domain.LoginVo;
import cn.aaa.result.JSONResult;
import cn.aaa.service.ICustomerService;
import cn.aaa.utils.BitStatesUtils;
import cn.aaa.utils.Level;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 客户 服务实现类
 * </p>
 *
 * @author axy
 * @since 2025-04-11
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private CustomerSummaryMapper customerSummaryMapper;
    @Autowired
    private UaaOpenFeign uaaOpenFeign;
    @Override
    public JSONResult register(Customer customer) {
        Customer customer1 =
                customerMapper.selectOne(new LambdaQueryWrapper<Customer>().eq(Customer::getOpenId, customer.getOpenId()));
        if(customer1 != null){
            return JSONResult.success();
        }else {
            //初始化乘客信息
            Date date = new Date();
            long id = IdUtil.getSnowflake(0L, 0L).nextId();
            Customer customer2 = new Customer();
            customer2.setOpenId(customer.getOpenId());
            customer2.setPhone(customer.getPhone());
            customer2.setCreateTime(date);
            customer2.setUpdateTime(date);
            customer2.setSex(1);
            customer2.setLevel(Level.qingtong.getNumber());
            customer2.setBitState(BitStatesUtils.OP_PHONE);
            customer2.setId(id);
            super.save(customer2);
            //初始化CustomerSummary
            CustomerSummary customerSummary = new CustomerSummary();
            customerSummary.setId(id);
            customerSummary.setTotalFine(new BigDecimal(0));
            customerSummary.setVoucherNumbers(0);
            customerSummary.setTotalOrders(0);
            customerSummary.setCancelOrders(0);
            customerSummaryMapper.insert(customerSummary);
            //远程调用
            LoginVo loginVo = new LoginVo();
            loginVo.setOpenId(customer.getOpenId());
            loginVo.setPhone(customer.getPhone());
            loginVo.setType(UserType.CUSTOMER);
            loginVo.setId(customer.getId());
            uaaOpenFeign.register(loginVo);
        }
        return JSONResult.success();
    }
}
